import { defineConfig } from '@tarojs/cli'
import path from 'path'
import devConfig from './dev'
import prodConfig from './prod'
import NutUIResolver from '@nutui/auto-import-resolver'
// 修改导入方式，使用CommonJS方式导入
const { default: Components } = require('unplugin-vue-components/webpack')
// import { UnifiedWebpackPluginV5 } from 'weapp-tailwindcss/webpack'
const { UnifiedWebpackPluginV5 } = require('weapp-tailwindcss/webpack')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
// const { AntDesignVueResolver } = require('unplugin-vue-components/resolvers');

// https://taro-docs.jd.com/docs/next/config#defineconfig-辅助函数
export default defineConfig(async (merge, { command, mode }) => {
  const baseConfig = {
    projectName: 'test-nutui-webpack-taro',
    date: '2025-6-15',
    designWidth(input) {
      // 配置 NutUI 375 尺寸
      if (input?.file?.replace(/\\+/g, '/').indexOf('@nutui') > -1) {
        return 375
      }
      // 全局使用 Taro 默认的 750 尺寸
      return 750
    },
    deviceRatio: {
      640: 2.34 / 2,
      750: 1,
      375: 2,
      828: 1.81 / 2,
    },
    sourceRoot: 'src',
    outputRoot: `dist/${process.env.TARO_ENV}`,

    plugins: ['@tarojs/plugin-html', '@tarojs/plugin-http'],
    alias: {
      '@': path.resolve(__dirname, '../src'),
    },
    defineConstants: {},
    copy: {
      patterns: [],
      options: {},
    },
    framework: 'vue3',
    compiler: {
      type: 'webpack5',
      prebundle: {
        enable: true,
      },
    },
    cache: {
      enable: true, // Webpack 持久化缓存配置，建议开启。默认配置请参考：https://docs.taro.zone/docs/config-detail#cache
    },
    mini: {
      postcss: {
        pxtransform: {
          enable: true,
          config: {},
        },
        cssModules: {
          enable: false, // 默认为 false，如需使用 css modules 功能，则设为 true
          config: {
            namingPattern: 'module', // 转换模式，取值为 global/module
            generateScopedName: '[name]__[local]___[hash:base64:5]',
          },
        },
      },
      cssLoaderOption: {
        // 开启 sourceMap 方便调试
        sourceMap: true,
      },
      optimizeMainPackage: {
        enable: true, // 开启主包优化
        // exclude: ['vendors'] // 排除公共模块到分包
      },
      compile: {
        exclude: [
          // path.resolve(__dirname, '..', 'src/utils/big-lib.js') // 排除大文件
          //  /vue-router/,
          // /@some-library-that-requires-router/
        ],
      },
      terser: {
        enable: true,
        config: {
          compress: { drop_console: true },
        },
      },
      webpackChain(chain) {
        // 复制这块区域到你的配置代码中 region start
        chain.merge({
          plugin: {
            install: {
              plugin: UnifiedWebpackPluginV5,
              args: [
                {
                  // 这里可以传参数
                },
              ],
            },
          },
        })
        chain.plugin('unplugin-vue-components').use(
          Components({
            resolvers: [NutUIResolver({ taro: true })],
          })
        )
        // 添加打包分析插件
        if (process.env.ANALYZE === 'true') {
          chain.plugin('analyzer').use(
            new BundleAnalyzerPlugin({
              analyzerMode: 'server',
              // analyzerPort: 8888,
              openAnalyzer: true,
              reportFilename: 'report.html',
              defaultSizes: 'parsed',
              generateStatsFile: false,
              statsFilename: 'stats.json',
              statsOptions: null,
              logLevel: 'info',
            })
          )
        }
        // 优化分包配置
        chain.optimization.splitChunks({
          chunks: 'all',
          minSize: 0,
          minRemainingSize: 0,
          minChunks: 1,
          maxAsyncRequests: 30,
          maxInitialRequests: Infinity,
          enforceSizeThreshold: 50000,
          automaticNameDelimiter: '~',
          name: false,
          cacheGroups: {
            vendors: {
              name: 'vendors',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: 'initial',
              reuseExistingChunk: true,
              enforce: true,
            },
            common: {
              name: 'common',
              minChunks: 2,
              priority: 5,
              chunks: 'initial',
              reuseExistingChunk: true,
            },
          },
        })
        // 移除未使用的导出（Tree Shaking）
        chain.optimization.usedExports(true)
        // 小程序构建时完全排除 ant-design-vue
        chain.resolve.alias.set('ant-design-vue', false)
        chain.merge({
          plugin: {
            install: {
              plugin: require('terser-webpack-plugin'),
              args: [
                {
                  terserOptions: {
                    compress: true, // 默认使用terser压缩
                    // mangle: false,
                    keep_classnames: true, // 不改变class名称
                    keep_fnames: true, // 不改变函数名称
                  },
                },
              ],
            },
          },
        })
      },
    },
    h5: {
      staticDirectory: 'static',
      // publicPath: '/',
      // devServer: {
      //   historyApiFallback: true
      // },
      // router: {
      //   mode: 'hash' // 启用浏览器路由模式
      // },
      output: {
        filename: 'js/[name].[fullhash:8].js',
        chunkFilename: 'js/[name].[chunkhash:8].js',
      },
      designWidth: 0, // 设置为 0 来禁用 px 转换
      miniCssExtractPluginOption: {
        ignoreOrder: true,
        filename: 'css/[name].[fullhash].css',
        chunkFilename: 'css/[name].[chunkhash].css',
      },
      postcss: {
        autoprefixer: {
          enable: true,
          config: {},
        },
        pxtransform: {
          enable: false,
          config: {
            platform: 'h5'
          }
        },
        cssModules: {
          enable: false, // 默认为 false，如需使用 css modules 功能，则设为 true
          config: {
            namingPattern: 'module', // 转换模式，取值为 global/module
            generateScopedName: '[name]__[local]___[hash:base64:5]',
          },
        },
      },
      webpackChain(chain) {
        chain.plugin('unplugin-vue-components').use(
          Components({
            resolvers: [
              NutUIResolver({ taro: true }),
              // AntDesignVueResolver({
              //   importStyle: false, // css in js
              // }),
            ],
          })
        )
        // 添加打包分析插件（H5环境）
        if (process.env.ANALYZE === 'true') {
          chain.plugin('analyzer').use(
            new BundleAnalyzerPlugin({
              analyzerMode: 'server',
              analyzerPort: 8889,
              openAnalyzer: true,
            })
          )
        }

        // 优化H5的打包配置
        chain.optimization.splitChunks({
          chunks: 'all',
          maxInitialRequests: Infinity,
          minSize: 20000,
          cacheGroups: {
            nutui: {
              name: 'chunk-nutui',
              test: /[\\/]node_modules[\\/]@nutui[\\/]/,
              priority: 20,
            },
            vendors: {
              name: 'chunk-vendors',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
            },
          },
        })
      },
    },
    rn: {
      appName: 'taroDemo',
      postcss: {
        cssModules: {
          enable: false, // 默认为 false，如需使用 css modules 功能，则设为 true
        },
      },
    },
  }
  if (process.env.NODE_ENV === 'development') {
    // 本地开发构建配置（不混淆压缩）
    return merge({}, baseConfig, devConfig)
  }
  // 生产构建配置（默认开启压缩混淆等）
  return merge({}, baseConfig, prodConfig)
})
